﻿#region License

// This file is part of Grawlix.
// 
// Grawlix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Grawlix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public
// License along with Grawlix.  If not, see
// <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using Grawlix.Concurrency;
using Grawlix.Geometry;
using Grawlix.Services.Resources;
using OpenTK.Graphics;

namespace Grawlix.Services.Rendering
{
	/// <summary>
	/// An <c>OpenGL</c>-based renderer.
	/// </summary>
	[Serializable]
	public sealed class GLRenderDevice :
		ServiceBase<IRenderDevice>, IRenderDevice, IDisposable
	{
		/// <summary>
		/// The object used to assert that operations happen on a
		/// particular thread.
		/// </summary>
		private ThreadAffinity _affinity = new ThreadAffinity();

		/// <summary>
		/// Whether the device has been disposed.
		/// </summary>
		private bool _disposed;

		/// <summary>
		/// Initializes a new instance of the 
		/// <see cref="GLRenderDevice"/> class.
		/// </summary>
		public GLRenderDevice()
		{
			GL.Enable(EnableCap.Texture2D);
		}

		/// <summary>
		/// Gets the thread affinity checker.
		/// </summary>
		/// <value>The object used to assert that operations happen on
		/// a particular thread.</value>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.
		/// </exception>
		public ThreadAffinity Affinity
		{
			get
			{
				if (_disposed)
					throw new ObjectDisposedException("GLRenderDevice");
				return _affinity;
			}
		}

		/// <summary>
		/// Clears the screen.
		/// </summary>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public void Clear()
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			//GL.Clear(ClearBufferMask.ColorBufferBit |
			//ClearBufferMask.StencilBufferBit);
			GL.Clear(ClearBufferMask.ColorBufferBit);
			GL.Clear(ClearBufferMask.StencilBufferBit);
		}

		/// <summary>
		/// Clips the screen to the specified area.
		/// </summary>
		/// <param name="area">The area to clip to.</param>
		/// <returns>A object that reverses the clipping on disposal.
		/// </returns>
		/// <remarks>Call this within a using statement.</remarks>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public IDisposable Clip(Rect area)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			var clip = new ClippingRaii(this);
			clip.Apply(); //area);
			return clip;
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing,
		/// releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// Releases unmanaged and - optionally - managed resources
		/// </summary>
		/// <param name="disposing"><c>true</c> to release both managed
		/// and unmanaged resources; <c>false</c> to release only
		/// unmanaged resources.</param>
		private void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
					_affinity = null;
				_disposed = true;
			}
		}

		/// <summary>
		/// Draws a flat-shaded rectangle on the screen.
		/// </summary>
		/// <param name="color">The color of the rectangle.</param>
		/// <param name="target">The target area to draw.</param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public void DrawRectangle(Color color, Rect target)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			GL.Disable(EnableCap.Texture2D);
			GL.Color4(color);
			GL.Rect((int)target.Left, (int)target.Bottom,
			        (int)target.Right, (int)target.Top);
		}

		/// <summary>
		/// Draws the given text.
		/// </summary>
		/// <param name="run">The run of text to draw.</param>
		/// <param name="origin">The origin with respect to the run
		/// layout.</param>
		/// <exception cref="ArgumentException">Incompatible font
		/// state.</exception>
		/// <exception cref="NotImplementedException">Text rendering is
		/// not currently implemented.</exception>
		private static void DrawText(TextRun run, Vector2 origin)
		{
			var glFont = run.Font.State as GLFontState;
			if (glFont == null)
			{
				throw new ArgumentException("Incompatible font state.",
				                            "run");
			}
			throw new NotImplementedException(
				"Text rendering is not currently implemented.");
		}

		/// <summary>
		/// Draws a series of already-laid-out text.
		/// </summary>
		/// <param name="runs">The series of text runs to draw.</param>
		/// <param name="origin">The origin with respect to the laid
		/// out text.</param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>runs</c> is
		/// null.</exception>
		public void DrawText(IEnumerable<TextRun> runs,
		                     Vector2 origin)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (runs == null)
				throw new ArgumentNullException("runs");
			_affinity.AssertCurrent();
			foreach (var run in runs)
				DrawText(run, origin);
		}

		/// <summary>
		/// Draws a piece of specified texture on the screen.
		/// </summary>
		/// <param name="texture">The texture to draw.</param>
		/// <param name="source">The area within the texture to use.
		/// </param>
		/// <param name="tint">The color to tint the texture.</param>
		/// <param name="target">Where to draw the rect on the screen.
		/// </param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>texture</c> is
		/// null.</exception>
		/// <exception cref="ArgumentException">Incompatible texture
		/// state.</exception>
		public void DrawTexture(ITextureState texture, Rect source,
		                        Color tint, Rect target)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (texture == null)
				throw new ArgumentNullException("texture");
			_affinity.AssertCurrent();
			var glTexture = (GLTextureState)texture;
			if (glTexture == null)
			{
				throw new ArgumentException(
					"Incompatible texture state.", "texture");
			}
			GL.Color4(tint);
			GL.Enable(EnableCap.Texture2D);
			glTexture.Bind();
			GL.Begin(BeginMode.Quads);
			GL.TexCoord2(source.Left, source.Top);
			GL.Vertex2(target.Left, target.Bottom);
			GL.TexCoord2(source.Right, source.Top);
			GL.Vertex2(target.Right, target.Bottom);
			GL.TexCoord2(source.Right, source.Bottom);
			GL.Vertex2(target.Right, target.Top);
			GL.TexCoord2(source.Left, source.Bottom);
			GL.Vertex2(target.Left, target.Top);
			GL.End();
		}

		/// <summary>
		/// Finishes the active render.
		/// </summary>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public void Finish()
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			GL.Flush();
			GL.Finish();
		}

		/// <summary>
		/// Loads the specified font into the renderer.
		/// </summary>
		/// <param name="font">The font to load.</param>
		/// <returns>The renderer font state.</returns>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>font</c> is
		/// null.</exception>
		public IFontState LoadFont(Font font)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (font == null)
				throw new ArgumentNullException("font");
			return new GLFontState(font);
		}

		/// <summary>
		/// Loads a texture into the renderer.
		/// </summary>
		/// <param name="image">The image to load.</param>
		/// <returns>The renderer texture state.</returns>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>image</c> is
		/// null.</exception>
		public ITextureState LoadTexture(WrappedImage image)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (image == null)
				throw new ArgumentNullException("image");
			return new GLTextureState(image);
		}

		/// <summary>
		/// Resizes the screen to the specified dimensions.
		/// </summary>
		/// <param name="dimensions">The dimensions to resize to.</param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public void Resize(Vector2 dimensions)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			GL.Viewport(0, 0, (int)dimensions.X, (int)dimensions.Y);
			GL.MatrixMode(MatrixMode.Projection);
			GL.LoadIdentity();
			GL.Ortho(0, dimensions.X, 0, dimensions.Y, (-1), 1);
		}

		/// <summary>
		/// Unloads the specified font.
		/// </summary>
		/// <param name="font">The font to unload.</param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>font</c> is
		/// null.</exception>
		/// <exception cref="ArgumentException">Incompatible font
		/// state.</exception>
		public void UnloadFont(IFontState font)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (font == null)
				throw new ArgumentNullException("font");
			var glFont = font as GLFontState;
			if (glFont == null)
			{
				throw new ArgumentException("Incompatible font state.",
				                            "font");
			}
			glFont.Unload();
		}

		/// <summary>
		/// Unloads the specified texture.
		/// </summary>
		/// <param name="texture">The texture to unload.</param>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		/// <exception cref="ArgumentNullException"><c>texture</c> is
		/// null.</exception>
		/// <exception cref="ArgumentException">Incompatible texture
		/// state.</exception>
		public void UnloadTexture(ITextureState texture)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			if (texture == null)
				throw new ArgumentNullException("texture");
			var glTexture = texture as GLTextureState;
			if (glTexture == null)
			{
				throw new ArgumentException(
					"Incompatible texture state.", "texture");
			}
			glTexture.Unload();
		}

		/// <summary>
		/// Zooms in to the specified rect, converting to the specified
		/// scale.
		/// </summary>
		/// <param name="source">The source rect to zoom into.</param>
		/// <param name="scale">The new rect to render to.</param>
		/// <returns>A object that reverses the zoom on disposal.
		/// </returns>
		/// <remarks>Call this within a using statement.</remarks>
		/// <exception cref="ObjectDisposedException">The object has
		/// already been disposed of.</exception>
		public IDisposable Zoom(Rect source, Rect scale)
		{
			if (_disposed)
				throw new ObjectDisposedException("GLRenderDevice");
			_affinity.AssertCurrent();
			var zoom = new ZoomingRaii(this);
			zoom.Apply(source, scale);
			return zoom;
		}

		/// <summary>
		/// A "resource acquisition is initialization" object for
		/// reversible clipping operations.
		/// </summary>
		[Serializable]
		private sealed class ClippingRaii : IDisposable
		{
			// <summary>
			// The area to clip to.
			// </summary>
			//private Rect _area;
			/// <summary>
			/// The renderer 
			/// </summary>
			private GLRenderDevice _render;

			// Methods
			/// <summary>
			/// Initializes a new instance of the 
			/// <see cref="ClippingRaii"/> class.
			/// </summary>
			/// <param name="render">The render device.</param>
			public ClippingRaii(GLRenderDevice render)
			{
				_render = render;
			}

			/// <summary>
			/// Applies clipping to the specified area.
			/// </summary>
			// <param name="area">The area to clip to.</param>
			public void Apply() //Rect area)
			{
				_render.Affinity.AssertCurrent();
				//_area = area;
			}

			/// <summary>
			/// Reverses the clip.
			/// </summary>
			public void Dispose()
			{
				if (_render != null)
				{
					_render.Affinity.AssertCurrent();
					_render = null;
				}
			}
		}

		/// <summary>
		/// A "resource acquisition is initialization" object for
		/// reversible zooming operations.
		/// </summary>
		[Serializable]
		private sealed class ZoomingRaii : IDisposable
		{
			/// <summary>
			/// The render device.
			/// </summary>
			private GLRenderDevice _render;

			/// <summary>
			/// Initializes a new instance of the <see cref="ZoomingRaii"/>
			/// class.
			/// </summary>
			/// <param name="render">The render device.</param>
			public ZoomingRaii(GLRenderDevice render)
			{
				_render = render;
			}

			/// <summary>
			/// Applies zooming to the specified source and scale.
			/// </summary>
			/// <param name="source">The source rectangle to zoom within.
			/// </param>
			/// <param name="scale">The scale to zoom to.</param>
			public void Apply(Rect source, Rect scale)
			{
				_render.Affinity.AssertCurrent();
				GL.MatrixMode(MatrixMode.Modelview);
				GL.PushMatrix();
				GL.Translate((source.Left * -1), (source.Bottom * -1),
				             0.0);
				GL.Scale((((double)1) / source.Dimensions.X),
				         (((double)1) / source.Dimensions.Y), 1.0);
				GL.Scale(scale.Dimensions.X, scale.Dimensions.Y, 1.0);
				GL.Translate(scale.Left, scale.Bottom, 0.0);
			}

			/// <summary>
			/// Reverses the zoom.
			/// </summary>
			public void Dispose()
			{
				if (_render != null)
				{
					_render.Affinity.AssertCurrent();
					GL.MatrixMode(MatrixMode.Modelview);
					GL.PopMatrix();
					_render = null;
				}
			}
		}
	}
}